package com.ly.auth.handler;

import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AbstractAuthenticationTargetUrlRequestHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author luka.zhou
 * @date 2024-3-10 10:29
 * @description Spring Security是使用Cookie和Session的记录用户。各个子系统的Cookie设置在同一路径下，在认证中心登出时，将Cookie一并删除，实现认证中心和各个子系统的登出。各子系统需要知道认证中心的登出地址 http.logout().logoutSuccessUrl("http://localhost:8001/uaa/logout");
 */
@Component
public class CustomLogoutSuccessHandler extends AbstractAuthenticationTargetUrlRequestHandler implements LogoutSuccessHandler {

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // 将子系统的cookie删掉
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                cookie.setMaxAge(0);
                cookie.setPath("/"); //各个子系统的cookie路径设置在/路径下，认证中心退出是删除/路径下的cookie。认证中心的cookie路径不能与子系统设置一样，如/，否则子系统认证不能通过。
                response.addCookie(cookie);
            }
        }
        super.handle(request, response, authentication);
    }
}
